package com.vf.cloud.server.redis.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


import com.jfinal.kit.StrKit;
import com.vf.cloud.common.constant.SoftPath;
import com.vf.cloud.common.pool.ProssPool;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Server implements Runnable{
	

	@Override
	public void run() {
		try {
			int status = executeCmd(String.format("%s/Redis/redis-server.exe %s/Redis/redis.windows.conf ", SoftPath.path,SoftPath.path));
			if (0 == status) {
				check();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	boolean isRun=false;
	public boolean isRunning() {
		while(true) {
			try {
				if(isRun) {
					break;
				}
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return isRun;
	}

	private int executeCmd(String command) throws IOException {
		try {
			if(StrKit.isBlank(ProssPool.getPid("6400"))) {
				Runtime runtime = Runtime.getRuntime();
				Process process = runtime.exec("cmd /c start /b " + command);
//				new Thread(new ConsoleThread(new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"))))
//						.start();
				return process.waitFor();
			}
			isRun=true;
			ProssPool.put("RedisServer", ProssPool.getPid("6400"));
			return 0;
		} catch (InterruptedException e) {
		}
		return -1;
	}

	/**
	 * 控制台
	 *
	 */
	class ConsoleThread implements Runnable {

		private BufferedReader bfr = null;

		public ConsoleThread(BufferedReader bfr) {
			this.bfr = bfr;
		}

		@Override
		public void run() {
			String line = null;
			try {
				while ((line = bfr.readLine()) != null) {
					log.info(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		}

	}

	private ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1);
	public void check() {
		scheduledExecutor.scheduleWithFixedDelay(new TimerTask() {
			@Override
			public void run() {
				String pid = ProssPool.getPid("6400");
				if (!StrKit.isBlank(pid)) {
					log.info("RedisServer >>> 启动成功，pid：" + pid);
					ProssPool.put("RedisServer", pid);
					scheduledExecutor.shutdown();
					isRun=true;
					return;
				}
			}
		}, 0, 1, TimeUnit.SECONDS);
	}

}
